//2009/08/08 13:15:29
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class HanoiTower
{
public:
    int moves(string pegA, string pegB, string pegC)
    {
        res = -1;
        recursive(pegA, pegB, pegC, 0);
        return res;

    }
    void recursive(string A, string B, string C, int times)
    {
        if (A.find(B) == -1 && A.find(C) ==-1)
        {
            if (B.find(A)== -1 && B.find(C) == -1)
            {
                if (C.find(A) == -1 && C.find(B) == -1)
                    if (res == -1 || res > times) res = times;
            }
        }
        char a = A[A.size()-1];
        char b = B[B.size()-1];
        char c = C[C.size()-1];
        int asz = A.size();
        int bsz = B.size();
        int csz = C.size();
        recursive(A.substr(0, asz-1), B.resize(bsz+1, a), C, times + 1);
        recursive(A.substr(0, asz-1), B, C.resize(csz+1, a), times + 1);
        recursive(A.resize(asz+1, b), B.substr(0, bsz-1), C, times + 1);
        recursive(A, B.substr(0, bsz-1), C.resize(csz+1, b), times + 1);
        recursive(A.resize(asz+1, c), B, C.substr(0, csz-1), times + 1);
        recursive(A, B.resize(bsz+1, c), C.substr(0, csz-1), times + 1);
    }
private:
    int res;
};
